package cn.xuhang.nav.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.xuhang.nav.dao.NavItemDao;
import cn.xuhang.nav.domain.NavItem;

import org.springframework.ui.Model;

@Service("navService")
public class NavItemService {
	@Autowired
	public NavItemDao navDao;

	Logger DEBUG = Logger.getLogger(NavItemService.class);


	/**
	 * 新增条目
	 *
	 * @param item
	 */
	public void insertNavItem(NavItem item) throws IOException {
		//查询URL是否存在
		String itemURL = item.getUrl();
		if (URLexsit(itemURL)) {
			throw new RuntimeException("URL:" + itemURL + " has existed!");
		}
		//获取favicon
//		List<String> urlList = this.getIcon(itemURL);
//		
//		urlList.add(this.getRootIconURL(itemURL).toString());
//		
//		if(item.getImgSrc() == null || "".equals(item.getImgSrc())){
//			item.setImgSrc(urlList.size()>0?urlList.get(0):"");
//		}
		if(item.getImgSrc() == null || "".equals(item.getImgSrc())){
			item.setImgSrc("http://localhost:8080/mynav/img/xfavicon.ico");
		}
		//model.addAttribute("iconURLs", urlList);

		//插入数据库
		this.navDao.insert(item);
	}

	/**
	 * 查询所有条目
	 *
	 * @return
	 */
	public List<NavItem> queryAllItems() {
		return this.navDao.query();
	}

	/**
	 * 查询URL是否已存在
	 *
	 * @param url
	 * @return
	 */
	private boolean URLexsit(String url) {
		return this.navDao.URLexist(url);
	}

	/**
	 * 根据URL地址获取当前页面的所有icon图标地址
	 *
	 * @param itemUrl
	 * @return
	 */
	public List<String> getIcon(String itemUrl) throws IOException {
		List<String> urls = new ArrayList();
		
		URL url = null;
		//DEBUG.debug(url.getProtocol());
		if (itemUrl.startsWith("http://")) {
			url = new URL(itemUrl);
		} else {
			url = new URL("http://" + itemUrl);
		}
		URLConnection conn = url.openConnection();
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line = null;//reader.readLine();
		String iconUrl = null;
		while ((line = reader.readLine()) != null) {
			iconUrl = null;
			if("</head>".equals(line)){
				break;
			}
			if (line.contains("icon") || line.contains("favicon") || line.contains("shortcut")) {
				Pattern p = Pattern.compile("href=\"\\S*?\"");
				Matcher m = p.matcher(line);
				if (m.find()) {
					String s = m.group();
					String token = s.substring(6, s.length() - 1);
					DEBUG.info(line);
					DEBUG.info("\t" + s);
					DEBUG.info("\t\t" + token);
					System.out.println(line + ">>>" + s + ">>>" + token);
					if (token.startsWith("http")) {
						iconUrl = token;
					} else {

						//System.out.println(token);
						if (token.startsWith("/") && itemUrl.endsWith("/")) {
							iconUrl = itemUrl + token.substring(1);
						} else if (!token.startsWith("/") && !itemUrl.endsWith("/")) {
							iconUrl = itemUrl + "/" + token.substring(1);
						} else {
							iconUrl = itemUrl + token;
						}
					}
					urls.add(iconUrl);
					continue;
					//break;
				}
			}
		}
		return urls;
	}

	/**
	 * 返回网站根目录下的favicon.ico图标
	 * @param urlString
	 * @return
	 * @throws MalformedURLException
	 */
	public URL getRootIconURL(String urlString) throws MalformedURLException {
		URL url = new URL(urlString);
		String protocol = url.getProtocol();
		String host = url.getHost();
		Integer port = url.getPort();
		StringBuffer sBuffer = new StringBuffer();
		if (port == -1) {
			sBuffer.append(protocol).append("://").append(host).append("/favicon.ico");
		} else {
			sBuffer.append(protocol).append("://").append(host).append(":").append(port).append("/favicon.ico");
		}
		URL iconURL = new URL(sBuffer.toString());
		return iconURL;
	}
	
	public NavItem queryNavItemById(Serializable id){
		return this.navDao.queryById(id);
	}
	
	/**
	 * 更新条目
	 * @throws IOException
	 */
	public void updateNavItem(NavItem item){
		this.navDao.update(item);
	}
	
	/**
	 * 删除
	 * @throws IOException
	 */
	public void deleteNavItem(Serializable id){
		this.navDao.delete(id);
	}
	
	
	//@Test
	public void testGetIconUrls() throws IOException {
		NavItemService service = new NavItemService();
		List<String> urls = service.getIcon("http://www.soulteary.com/");
		for(String url : urls){
			System.out.println(url);
		}
	}
	
	//@Test
	public void testIconPath() throws IOException, URISyntaxException {
		URL url = new URL("http://q.cnblogs.com/q/21013/");
		System.out.println("host: " + url.getHost());
		System.out.println("path: " + url.getPath());
		System.out.println("protocol: " + url.getProtocol());
		System.out.println("authority: " + url.getAuthority());
		System.out.println("file: " + url.getFile());
		System.out.println("query: " + url.getQuery());
		System.out.println("ref: " + url.getRef());
		System.out.println("userInfo: " + url.getUserInfo());
		System.out.println("content: " + url.getContent());
		System.out.println("port: " + url.getPort());
		System.out.println("externalForm: " + url.toExternalForm());
		System.out.println("********************************");
		URI uri = url.toURI();
		System.out.println("host: " + uri.getHost());
		System.out.println("path: " + uri.getPath());
		System.out.println("authority: " + uri.getAuthority());
		System.out.println("query: " + uri.getQuery());
		System.out.println("userInfo: " + uri.getUserInfo());
		System.out.println("port: " + uri.getPort());
		System.out.println();
		System.out.println("fragment: " + uri.getFragment());
		System.out.println("scheme: " + uri.getScheme());
		System.out.println("isAbsolute: " + uri.isAbsolute());
		System.out.println("isOpaque: " + uri.isOpaque());
		System.out.println("serverAuthority: " + uri.parseServerAuthority());
	}
}